<?php

namespace app\api\command;

use app\admin\model\share\ShareUser;
use app\common\model\PrepaidLogs;
use think\console\Input;
use think\console\Output;
use think\console\Command;
use addons\shopro\model\Order;

class Prepaid extends Command
{
    protected function configure()
    {
        $this->setName('order-payment-prepaid')->setDescription('同步易付卷订单支付状态');
    }

    protected function execute(Input $input, Output $output)
    {
        PrepaidLogs::where('status', 0)->chunk(100, function ($logs) {
            foreach ($logs as $log) {
                $order = Order::get(['id' => $log->order_id]);
                if (!empty($order) && in_array($order->status, [1, 2])) {
                    $log->status = 1;
                    $log->pay_time = time();
                    $log->save();
                } elseif (!empty($order) && $order->status == '-1') {
                    // 订单取消
                    $log->status = 2;
                    $log->save();
                    // 取消推广人身份
                    $user =(new ShareUser())->get(['user_id'=>$order->user_id]); // 分销用户
                    if (!empty($user) && $user['role'] == 1) {
                        // 如果该分销用户为推广人，取消推广人身份
                        $user->role = 0;
                        $user->save();
                    }
                }
            }
        });

        echo "ok".date('Y-m-m H:i:s') . PHP_EOL;
    }
}